import utils from '@/utils/index';
import Taro from '@tarojs/taro';

const PayStatus = {
  success: 'success',
  cancel: 'cancel',
  failed: 'failed',
};

const pay = async (orderId, payResult) => {
  const extra = JSON.parse(JSON.parse(payResult).extra);

  return new Promise((resolve) => {
    const successData = { status: PayStatus.success, orderId };
    const cancelData = { status: PayStatus.cancel, orderId };
    const failedData = { status: PayStatus.failed, orderId };

    if (Taro.$isH5) {
      utils.WXPayByH5(
        extra,
        (data) => {
          resolve({ ...successData, ...data });
        },
        (data) => {
          resolve({ ...cancelData, ...data });
        },
        (data) => {
          resolve({ ...failedData, ...data });
        },
        orderId,
      );

      return;
    }

    Taro.requestPayment({
      ...extra,
      success: (data) => {
        resolve({ ...successData, ...data });
      },
      fail: function (rlt) {
        if (rlt.errMsg && rlt.errMsg == 'requestPayment:fail cancel') {
          resolve({ ...cancelData, ...rlt });
        } else {
          resolve({ ...failedData, ...rlt });
        }
      },
    });
  });
};

const getPrePayBase = () => {
  let openId = utils.getLocalOpenId();

  return {
    channel: Taro.$isH5 ? 'weixin-h5-shop' : 'weixin-mini-shop',
    openId,
  };
};

export { PayStatus, pay, getPrePayBase };
